//
//  CustomerViewController.m
//  Kfangchan
//
//  Created by liran on 14/11/5.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "CustomerViewController.h"
#import "CustomerTableViewCell.h"
#import "CustomerDetailViewController.h"

@interface CustomerViewController () {
    UITapGestureRecognizer *tap;
    UIView *emptyView;
}

@property (nonatomic) int cpage;
@property (strong, nonatomic) NSMutableArray *customerArray;

@property (strong, nonatomic) UIView *searchView;
@property (strong, nonatomic) UITextField *searchTextField;

@property (strong, nonatomic) IBOutlet UITableView *customerTableView;

@end

@implementation CustomerViewController
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.searchView) {
        self.searchView.hidden = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"我的客户"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"building_top_left.png"] Target:nil Selector:nil];
    self.navigationItem.rightBarButtonItem = [[Theam currentTheam] navigationBarRightButtonItemWithImage:[UIImage imageNamed:@"customer_search.png"] Target:self Selector:@selector(showSearchView)];
    
    self.customerTableView.size = CGSizeMake(self.customerTableView.width, ScreenHeight - 70);
    
    __weak CustomerViewController *weak_self = self;
    //header
    [self.customerTableView addHeaderWithCallback:^{
        [weak_self initList];
    } andIsChat:YES andIsOther:YES];
    //footer
    [self.customerTableView addFooterWithCallback:^{
        weak_self.cpage++;
        [weak_self loadData];
    }];
    
    [self initEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (theApp.reloadCustomerList) {
        self.customerArray = nil;
        theApp.reloadCustomerList = NO;
    }
    if (self.customerArray == nil || self.customerArray.count == 0) {
        [self initList];
    }
    
    if (self.searchView) {
        self.searchView.hidden = NO;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"recommend_success" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 列表相关
#pragma mark 初始化
- (void)initList {
    self.cpage = 1;
    if (self.customerArray == nil) {
        self.customerArray = [NSMutableArray array];
    }
    [self loadData];
}

#pragma mark 加载数据
- (void)loadData {
    __weak CustomerViewController *weak_self = self;
    NSString *keyWord = @"";
    if (self.searchTextField != nil) {
        keyWord = self.searchTextField.text;
    }
    NSDictionary *param = @{
                            @"cpage": [NSString stringWithFormat:@"%i", self.cpage],
                            @"name": keyWord};
    MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_CUSTOMER_LIST completionHandler:^(id responseObject) {
        
        if (weak_self.cpage==1) {
            [weak_self.customerArray removeAllObjects];
        }
        
        id totalPages = [responseObject objectForKey:@"totalPages"];
        if (weak_self.cpage >= [totalPages intValue]) {
            [weak_self.customerTableView setFooterHidden:YES];
        } else {
            [weak_self.customerTableView setFooterHidden:NO];
        }

        id list = [responseObject objectForKey:@"list"];
        if (![list isKindOfClass:[NSNull class]]) {
            CustomerList *customerList = [[CustomerList alloc] initWithArray:list];
            [weak_self.customerArray addObjectsFromArray:customerList.array];
        }
        
        if (weak_self.customerArray.count == 0) {
            [weak_self.customerTableView addSubview:emptyView];
        } else {
            [emptyView removeFromSuperview];
        }
        
        [weak_self.customerTableView reloadData];
    } errorHandler:^(NSError *error) {
        showCustomAlertMessage(@"网路错误");
        [weak_self.customerTableView headerEndRefreshing];
        [weak_self.customerTableView setFooterHidden:YES];
    } finishHandler:^(id responseObject) {
        [weak_self.customerTableView headerEndRefreshing];
        [weak_self.customerTableView footerEndRefreshing];
    }];
    [self.opHandlers addObject:operation];
}

#pragma mark - UITableVIew
#pragma mark 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.customerArray count];
}

#pragma mark 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"CustomerTableViewCell";
    
    Customer *entity = self.customerArray[indexPath.row];
    
    CustomerTableViewCell *cell = (CustomerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        NSArray *cells = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
        cell = [cells objectAtIndex:0];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [cell initCell:entity];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = (int)[indexPath row];
    Customer *customer = self.customerArray[row];
    if (customer) {
        CustomerDetailViewController *cdvc = [[CustomerDetailViewController alloc] init];
        cdvc.entity = customer;
        cdvc.hidesBottomBarWhenPushed = YES;
        if (self.searchView) {
            self.searchView.hidden = YES;
        }
        [self.navigationController pushViewController:cdvc animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark -
#pragma mark 空结果页
- (void)initEmptyView {
    if(emptyView == nil) {
        emptyView = [[UIView alloc] initWithFrame:self.view.bounds];
        UIImageView *emptyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, 320, 187)];
        emptyImageView.image = [UIImage imageNamed:@"customer_empty.png"];
        [emptyView addSubview:emptyImageView];
    }
}

#pragma mark -
#pragma mark 搜索相关
- (void)showSearchView {
    if (self.searchView == nil) {
        self.searchView = [[UIView alloc] init];
        CGRect frame = CGRectMake(0, 0, 320, 44);
        if (isIOS7) {
            frame = CGRectMake(0, 20, 320, 44);
        }
        [self.searchView.layer setContents:(id)[[UIImage imageNamed:@"nav_bg.png"] CGImage]];
        self.searchView.frame = frame;
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame = CGRectMake(10, 3, 40, 40);
        [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(hideSearchView) forControlEvents:UIControlEventTouchUpInside];
        [self.searchView addSubview:backButton];
        
        UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(60, frame.size.height - 30 - 5, 200, 30)];
        searchView.backgroundColor = [UIColor whiteColor];
        searchView.layer.cornerRadius = 4.0;
        
        self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, 190, 30)];
        self.searchTextField.delegate = self;
        self.searchTextField.returnKeyType = UIReturnKeySearch;
        self.searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.searchTextField.enablesReturnKeyAutomatically = YES;
        [self.searchTextField addTarget:self action:@selector(tapBackground) forControlEvents:UIControlEventTouchDown];
        [searchView addSubview:self.searchTextField];
        [self.searchView addSubview:searchView];
        
        UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        searchButton.frame = CGRectMake(265, frame.size.height - 30 - 5, 50, 30);
        [searchButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
        [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
        [self.searchView addSubview:searchButton];
    }

    [theApp.window addSubview:self.searchView];
}

- (void)hideSearchView {
    self.searchTextField.text = @"";
    [self.searchView removeFromSuperview];
}

- (void)search {
    [self hideKeyboard];
    [self initList];
}


- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self searchTextFieldDoneEditing:textField];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self search];
    return YES;
}

#pragma mark -
#pragma mark return键关闭键盘
- (void)searchTextFieldDoneEditing:(id)sender {
    [self hideKeyboard];
}

#pragma mark 触摸背景关闭键盘
-(void)tapBackground {
    if (tap == nil) {
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];//定义一个手势
        [tap setNumberOfTouchesRequired:1];//触击次数这里设为1
    }
    
    if([[self.view gestureRecognizers] containsObject:tap]) {
        return;
    }
    [self.view addGestureRecognizer:tap];
}

-(void)hideKeyboard {
    [self.searchTextField resignFirstResponder];
    [self.view removeGestureRecognizer:tap];
}

#pragma mark -
#pragma mark
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
